<template>
  <div class="question-manage-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/manage/' + id }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>题库管理</el-breadcrumb-item>
      <el-breadcrumb-item>题库编辑</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card" shadow="hover">
      <!-- 操作区域 -->
      <div class="action-bar">
        <el-button type="primary" icon="el-icon-plus" @click="addQuestionDialogVisible = true">添加题目</el-button>
        <el-button type="success" icon="el-icon-upload" @click="showBatchImport = true">批量导入</el-button>
       
        <el-button 
          type="danger" 
          icon="el-icon-delete" 
          @click="handleBatchDelete" 
          :disabled="selectedQuestions.length === 0">
          批量删除 ({{ selectedQuestions.length }})
        </el-button>
        
        <el-select v-model="queryInfo.categoryId" placeholder="请选择题目分类" clearable style="width: 220px; margin-left: 20px;" @change="handleFilterChange">
          <el-option
            v-for="item in questionCategories"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #f56c6c;" @click.stop="deleteCategory(item.id)">
              <i class="el-icon-delete"></i>
            </span>
          </el-option>
          <el-option class="add-category-option">
            <div style="display: flex; align-items: center; justify-content: space-between;" @click="showAddCategoryDialog">
              <span>添加分类</span>
              <i class="el-icon-plus" style="color: #409EFF;"></i>
            </div>
          </el-option>
        </el-select>

        <!-- 添加分类对话框 -->
        <el-dialog
          title="添加题目分类"
          :visible.sync="addCategoryDialogVisible"
          width="30%">
          <el-form :model="categoryForm" :rules="categoryRules" ref="categoryForm" label-width="100px">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="categoryForm.name" placeholder="请输入分类名称" style="width: 80%;"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCategory">确 定</el-button>
          </span>
        </el-dialog>
        
        <el-select v-model="queryInfo.type" placeholder="请选择题目类型" clearable style="width: 200px; margin-left: 20px;" @change="handleFilterChange">
          <el-option label="选择题" value="选择题"></el-option>
          <el-option label="填空题" value="填空题"></el-option>
          <el-option label="问答题" value="问答题"></el-option>
        </el-select>
      </div>


      <!-- 题目表格 -->
      <question-table
        :data="questionList"
        :loading="loading"
        :pagination="{ currentPage: queryInfo.pageNum, pageSize: queryInfo.pageSize, total: total }"
        @selection-change="handleSelectionChange"
        @edit="handleEdit"
        @delete="handleDelete"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 添加题目对话框 -->
      <add-question-dialog
        :visible.sync="addQuestionDialogVisible"
        @submit="handleAddSubmit"
        @close="resetAddForm"
      />

      <!-- 编辑题目对话框 -->
      <edit-question-dialog
        :visible.sync="editQuestionDialogVisible"
        :form="editQuestionForm"
        :is-edit="true"
        @submit="handleEditSubmit"
        @cancel="editQuestionDialogVisible = false"
        @close="editQuestionDialogClosed"
      />

      <!-- 批量导入对话框 -->
      <batch-import-dialog
        :categoryId="queryInfo.categoryId"
        :questionCategories="questionCategories"
        :visible.sync="showBatchImport"
      />
    </el-card>
  </div>
</template>

<script>
import SessionManager from '../../../utils/sessionManager.js'
import RichTextEditor from '../../common/RichTextEditor.vue'
import axios from 'axios'
import QuestionTable from './components/QuestionTable.vue'
import AddQuestionDialog from './components/AddQuestionDialog.vue'
import EditQuestionDialog from './components/EditQuestionDialog.vue'
import BatchImportDialog from './components/BatchImportDialog.vue'

export default {
  name: 'ManageTestAdd',
  components: {
    RichTextEditor,
    QuestionTable,
    AddQuestionDialog,
    EditQuestionDialog,
    BatchImportDialog
  },
  data() {
    return {
      showBatchImport: false,
      id: window.sessionStorage.getItem('id'),
      userInfo: {},
      queryInfo: {
        type: '',
        categoryId: '',
        keyword: '',
        pageNum: 1,
        pageSize: 5
      },
      questionCategories: [], // 题目分类列表
      categoryForm: {
        name: ''
      },
      categoryRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      },
      addCategoryDialogVisible: false,
      questionList: [],
      total: 0,
      // 移除pagination对象，只用queryInfo
      // pagination: {
      //   currentPage: 1,
      //   pageSize: 10,
      //   total: 0
      // },
      selectedQuestions: [],
      addQuestionDialogVisible: false,
      addQuestionFileDialogVisible: false,
      editQuestionDialogVisible: false,
      fullTextDialogVisible: false,
      fullTextContent: '',
      fullTextTitle: '',
      loading: false,
      excelFileList: [], // Excel文件上传列表
      addQuestionForm: {
        categoryId: null,
        type: '选择题', // 默认为选择题
        answerTime: 60, // 设置默认值为60秒
        questionText: '<p></p>', // 题干，使用富文本格式
        answer: '<p></p>', // 填空题和问答题的答案，使用富文本格式
        score: 10 // 题目默认分数
      },
      editQuestionForm: { // 编辑题目表单
        id: null,
        type: null,
        categoryId: null,
        answerTime: 60,
        questionText: '<p></p>', // 题干，使用富文本格式
        answer: '<p></p>', // 填空题和问答题的答案，使用富文本格式
        score: 10 // 题目默认分数
      },
      editQuestionFormRules: { // 编辑表单验证规则
        type: [{ required: true, message: '请选择题目类型', trigger: 'blur' }],
        answerTime: [
          { required: true, message: '请输入答题时间', trigger: 'blur' },
          { type: 'number', message: '答题时间必须为数字', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value === '' || value === undefined || value === null) {
              callback(new Error('请输入答题时间'))
            } else if (!Number.isInteger(Number(value))) {
              callback(new Error('答题时间必须为整数'))
            } else if (Number(value) < 1) {
              callback(new Error('答题时间必须大于等于1'))
            } else {
              callback()
            }
          }, trigger: 'blur' }
        ]
      },
      addQuestionFormRules: {
        categoryId: [{ required: true, message: '请选择题目分类', trigger: 'blur' }],
        type: [{ required: true, message: '请选择题目类型', trigger: 'blur' }],
        answerTime: [
          { required: true, message: '请输入答题时间', trigger: 'blur' },
          { type: 'number', message: '答题时间必须为数字', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value === '' || value === undefined || value === null) {
              callback(new Error('请输入答题时间'))
            } else if (!Number.isInteger(Number(value))) {
              callback(new Error('答题时间必须为整数'))
            } else if (Number(value) < 1) {
              callback(new Error('答题时间必须大于等于1'))
            } else {
              callback()
            }
          }, trigger: 'blur' }
        ],
        questionText: [{ required: true, message: '请输入题目文本', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入题目答案', trigger: 'blur' }],
    
      }
    }
  },
  created () {
    this.id = parseInt(this.$route.params.id)
    this.activePath = window.sessionStorage.getItem('activePath')
    this.initializeData()
 
  },
  mounted() {
  },
  methods: {
    async initializeData() {
    try {
      await this.getQuestionCategories()
      await this.getQuestionList()
    } catch (error) {
      console.error('初始化数据失败:', error)
      this.$message.error('初始化数据失败，请稍后重试')
    }
  },
    // 获取题目分类列表
    async getQuestionCategories() {
      try {
        console.log('开始请求题目分类...')
        const response = await this.$http.get('/question-category/list')
        console.log('收到响应:', response)
        
        // 检查响应是否有效
        if (!response || !response.data) {
          console.error('无效的响应:', response)
          this.$message.error('获取题目分类失败：无效的响应')
          return
        }
        
        const res = response.data
        console.log('响应数据:', res)
        
        // 确保data存在且是数组
        if (!res.data || !Array.isArray(res.data)) {
          console.error('无效的分类数据:', res)
          this.$message.error('获取题目分类失败：数据格式错误')
          return
        }
        
        // 转换数据格式
        this.questionCategories = res.data.map(item => ({
          id: item.id,
          name: item.questionCategory
        }))

        if (this.questionCategories.length > 0) {
        this.queryInfo.categoryId = this.questionCategories[0].id;
      }
        console.log('成功获取题目分类:', this.questionCategories)
      } catch (err) {
        console.error('获取题目分类失败:', err)
        this.$message.error(`获取题目分类失败: ${err.message || '未知错误'}`)
      }
    },
    // 转义正则表达式特殊字符
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    },
    
    // 显示添加分类对话框
    showAddCategoryDialog() {
      this.categoryForm.name = '';
      this.addCategoryDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.categoryForm && this.$refs.categoryForm.clearValidate();
      });
    },
    
    // 添加分类
    async addCategory() {
      this.$refs.categoryForm.validate(async (valid) => {
        if (!valid) return;
        
        try {
          const response = await this.$http.post('/question-category/add', {
            questionCategory: this.categoryForm.name
          });
          
          if (response.data && response.data.code === 200) {
            this.$message.success('添加分类成功');
            this.addCategoryDialogVisible = false;
            this.getQuestionCategories(); // 刷新分类列表
          } else {
            this.$message.error(response.data.msg || '添加分类失败');
          }
        } catch (error) {
          console.error('添加分类失败:', error);
          this.$message.error('添加分类失败: ' + (error.response?.data?.message || error.message));
        }
      });
    },
    
    // 删除分类
    async deleteCategory(id) {
      this.$confirm('确定要删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await this.$http.delete(`/question-category/delete/${id}`);
          
          if (response.data && response.data.code === 200) {
            this.$message.success('删除分类成功');
            this.getQuestionCategories(); // 刷新分类列表
            // 如果当前选中的分类被删除，清空选择
            if (this.queryInfo.categoryId === id) {
              this.queryInfo.categoryId = '';
            }
          } else {
            this.$message.error(response.data.msg || '删除分类失败');
          }
        } catch (error) {
          console.error('删除分类失败:', error);
          this.$message.error('删除分类失败: ' + (error.response?.data?.message || error.message));
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    // 处理分类对话框关闭
    handleCategoryDialogClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    // 获取token方法
    getToken() {
      return SessionManager.getToken() || '';
    },
    
    // 根据题目类型返回对应的标签类型
    getTagType(type) {
      const typeMap = {
        '选择题': 'primary',
        '填空题': 'success',
        '问答题': 'warning'
      };
      return typeMap[type] || 'info';
    },
    
    // 显示全文对话框
    showFullText(text, title) {
      this.$alert(text, title, {
        confirmButtonText: '确定',
        customClass: 'full-text-dialog',
        dangerouslyUseHTMLString: false,
        closeOnClickModal: true
      });
    },
    
    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedQuestions = selection;
    },
    
    // 关闭编辑对话框
    editQuestionDialogClosed() {
      this.editQuestionDialogVisible = false;
      this.fileList = [];
      // 重置表单
      this.editQuestionForm = {
        id: null,
        type: null,
        answerTime: 60,
        questionText: '<p></p>', // 题干，使用富文本格式
        answer: '<p></p>', // 填空题和问答题的答案，使用富文本格式
        score: 10 // 题目默认分数
      };
    },
    
    // 提交编辑表单
    submitEditQuestionForm() {
      this.loading = true;
      
      // 创建表单数据
      const formData = new FormData();
      
      // 添加题目基本信息
      formData.append('id', this.editQuestionForm.id);
      formData.append('type', this.editQuestionForm.type);
      formData.append('answerTime', this.editQuestionForm.answerTime);
      formData.append('questionText', this.editQuestionForm.questionText);
      formData.append('answer', this.editQuestionForm.answer);
      formData.append('score', this.editQuestionForm.score);
      
      // 添加教师ID
      const teacherId = SessionManager.getUserId();
      formData.append('teacherId', teacherId);
    

      // 发送请求
      this.$http.put('/question/update', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success('更新成功');
          this.editQuestionDialogVisible = false;
          this.getQuestionList(); // 刷新列表
        } else {
          this.$message.error('更新失败: ' + (res.data.msg || '未知错误'));
        }
      }).catch(err => {
        console.error('更新题目出错:', err);
        this.$message.error('网络错误，请稍后重试');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 删除单个题目
    deleteQuestion(id) {
      this.$confirm('确定要删除此题目吗？删除后不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        this.$http.delete(`/question/delete/${id}`).then(res => {
          if (res.data.code === 200) {
            this.$message.success('删除成功');
            this.getQuestionList(); // 刷新列表
          } else {
            this.$message.error('删除失败: ' + (res.data.msg || '未知错误'));
          }
        }).catch(err => {
          console.error('删除题目出错:', err);
          this.$message.error('网络错误，请稍后重试');
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    // 批量删除题目
    batchDeleteQuestions() {
      if (this.selectedQuestions.length === 0) {
        return this.$message.warning('请先选择要删除的题目');
      }
      
      this.$confirm(`确定要删除选中的 ${this.selectedQuestions.length} 个题目吗？删除后不可恢复！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取所有选中题目的ID
        const ids = this.selectedQuestions.map(item => item.id);
        
        this.loading = true;
        this.$http.post('/question/batchDelete', { ids }).then(res => {
          if (res.data.code === 200) {
            this.$message.success(`成功删除 ${ids.length} 个题目`);
            this.getQuestionList(); // 刷新列表
          } else {
            this.$message.error('批量删除失败: ' + (res.data.msg || '未知错误'));
          }
        }).catch(err => {
          console.error('批量删除题目出错:', err);
          this.$message.error('网络错误，请检查网络连接后重试');
        }).finally(() => {
          this.loading = false;
          this.selectedQuestions = []; // 清空选择
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    // 发布单个题目
    publishSingleQuestion(id) {
      this.$confirm('确定要发布此题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载状态
        this.loading = true;
        
        // 调用API发布题目
        this.$http.post(`/question/publish/${id}`).then(res => {
          if (res.data.code === 200) {
            this.$message.success('题目发布成功');
            // 刷新题目列表
            this.getQuestionList();
          } else {
            this.$message.error('发布失败: ' + (res.data.msg || '未知错误'));
          }
        }).catch(err => {
          console.error('发布题目出错:', err);
          this.$message.error('网络错误，请稍后重试');
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.$message.info('已取消发布');
      });
    },
    // 获取题库数据
    async getQuestionList() {
      this.loading = true;
      try {
        // 获取用户角色和教师ID
        const userRole = SessionManager.getUserRole();
        const teacherId = SessionManager.getUserId();

        if (this.queryInfo.categoryId === '') {
          
        }
        
        // 准备请求参数
        const params = {
          pageNum: this.queryInfo.pageNum || 1,
          pageSize: this.queryInfo.pageSize || 10,
          keyword: this.queryInfo.keyword || '',
          type: this.queryInfo.type || '',
          categoryId: this.queryInfo.categoryId || ''
        };
        
        // 如果是教师角色，只查询该教师创建的题目
        if (userRole === '1') {
          params.teacherId = teacherId;
        }
        
        console.log('请求参数:', params);
        
        // 发送请求
        const res = await this.$http.get('/question/list', { params });
        
        if (res.data.code !== 200) {
          throw new Error(res.data.msg || '获取题库数据失败');
        }
        
        console.log('获取的题目数据:', res.data);
        
        // 处理返回的数据
        const responseData = res.data.data || {}; // 获取data对象
        
        // 处理分类名称
        const records = responseData.records || responseData.items || [];
        
        // 确保 questionCategories 已经加载
        if (!this.questionCategories || this.questionCategories.length === 0) {
          await this.getQuestionCategories();
        }
        
        // 创建分类ID到名称的映射
        const categoryMap = {};
        this.questionCategories.forEach(cat => {
          categoryMap[cat.id] = cat.name || `未知分类(${cat.id})`;
        });
        
        // 为每条记录添加 categoryName 字段
        this.questionList = records.map(item => ({
          ...item,
          categoryName: categoryMap[item.categoryId] || `未知分类(${item.categoryId})`
        }));
        
        this.total = responseData.total || 0; // 获取总记录数
        
        // 更新分页信息
        // this.pagination = {
        //   currentPage: this.queryInfo.pageNum,
        //   pageSize: this.queryInfo.pageSize,
        //   total: this.total
        // };
        
        return res;
      } catch (err) {
        console.error('获取题目列表出错:', err);
        const errorMsg = err.response?.data?.msg || err.message || '网络错误，请稍后重试';
        this.$message.error(`获取题目列表失败: ${errorMsg}`);
        throw err; // 抛出错误以便调用方处理
      } finally {
        this.loading = false;
      }
    },
    // 处理筛选条件变化
    handleFilterChange() {
      // 重置到第一页
      this.queryInfo.pageNum = 1;
      // 重新获取题目列表
      this.getQuestionList();
    },
    
    // 页面大小变化
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.queryInfo.pageNum = 1; // 重置到第一页
      this.getQuestionList();
    },
    // 当前页变化
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getQuestionList();
    },
    // 添加题目
    addQuestion () {
      this.addQuestionDialogVisible = true
    },
    // 添加题库
    addQuestionFile () {
      console.log('=== 点击批量导入题库按钮 ===');
      console.log('当前selectedFile:', this.selectedFile);
      console.log('当前excelFileList:', this.excelFileList);
      console.log('当前按钮禁用状态:', !this.selectedFile);
      console.log('打开批量导入对话框...');
      
      this.addQuestionFileDialogVisible = true
      
      // 监听对话框打开后的状态
      this.$nextTick(() => {
        console.log('对话框已打开，当前状态:');
        console.log('addQuestionFileDialogVisible:', this.addQuestionFileDialogVisible);
        console.log('selectedFile:', this.selectedFile);
        console.log('excelFileList:', this.excelFileList);
      });
    },
    // 关闭添加题目对话框
    addQuestionDialogClosed () {
      this.addQuestionFileDialogVisible = false
      this.restAddForm()
    },
    // 重置表单
    restAddForm () {
      this.addQuestionForm = {
        categoryId: null,
        type: '选择题', // 默认为选择题
        answerTime: 60, // 设置默认值为60秒
        questionText: '<p></p>', // 题干，使用富文本格式
        answer: '<p></p>', // 填空题和问答题的答案，使用富文本格式 
        score: 10 // 题目默认分数
      }
    },
    // 处理添加题目对话框的提交
    handleAddSubmit(formData) {
      this.addQuestionForm = { ...formData };
      console.log('添加题目表单数据:', this.addQuestionForm);
      this.submitQuestionForm();
    },
    
    // 处理编辑题目
    handleEdit(row) {
      console.log('编辑题目:', row);
      // 将行数据填充到表单
      this.editQuestionForm = { ...row };
      // 打开编辑对话框
      this.editQuestionDialogVisible = true;
    },
    
    // 处理编辑表单提交
    handleEditSubmit(formData) {
      console.log('提交编辑表单:', formData);
      // 更新题目数据
      this.editQuestionForm = { ...formData };
      // 提交表单
      this.submitEditQuestionForm();
      // 关闭对话框
      this.editQuestionDialogVisible = false;
    },
    
    // 处理删除题目
    handleDelete(row) {
      this.$confirm('确定要删除这道题目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteQuestion(row.id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    
    // 提交添加题目表单
    submitQuestionForm() {
      // 准备请求数据
      const formData = new FormData();
      formData.append('categoryId', this.addQuestionForm.categoryId);
      formData.append('type', this.addQuestionForm.type);
      formData.append('answerTime', this.addQuestionForm.answerTime || 60);
      formData.append('questionText', this.addQuestionForm.questionText || '');
      formData.append('answer', this.addQuestionForm.answer || '');
      formData.append('score', this.addQuestionForm.score || 10);
      formData.append('TeacherID', SessionManager.getUserId() || '1'); // 注意这里的字段名与后端一致

      console.log('提交的表单数据:');
      for (let [key, value] of formData.entries()) {
        console.log(key + ': ' + value);
      }

      // 显示加载状态
      this.loading = true;
      this.$message.info('正在提交题目，请稍候...');

      // 发送请求
      this.$http.post('/question/insert', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': 'Bearer ' + this.getToken()
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success('添加题目成功');
          this.addQuestionDialogVisible = false;
          this.restAddForm();
          this.getQuestionList(); // 刷新列表
        } else {
          this.$message.error('添加失败: ' + (res.data.msg || '未知错误'));
        }
      }).catch(err => {
        console.error('提交题目请求失败:', err);
        this.$message.error('网络错误，请稍后重试');
      }).finally(() => {
        this.loading = false;
      });
    },
    // 当用户选择时触发
    handleFileChange (file, fileList) {
     // alert('handleFileChange被调用了！文件名: ' + (file ? file.name : '无文件'));
      console.log('=== handleFileChange 开始 ===');
      console.log('接收到的file对象:', file);
      console.log('接收到的fileList:', fileList);
      console.log('file.raw:', file.raw);
      console.log('file.name:', file.name);
      
      // 检查文件类型
      const allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
      const fileExtension = file.name.split('.').pop().toLowerCase()
      console.log('文件扩展名:', fileExtension);
      console.log('文件MIME类型:', file.raw ? file.raw.type : 'file.raw为空');
      console.log('允许的MIME类型:', allowedTypes);
      
      if (!allowedTypes.includes(file.raw.type) && !['xls', 'xlsx'].includes(fileExtension)) {
        console.log('❌ 文件格式验证失败');
        this.$message.error('文件格式不正确，请上传 .xlsx 或 .xls 格式的文件')
        this.excelFileList = [] // 清空文件列表
        console.log('selectedFile 清空为:', this.selectedFile);
        return
      }
      console.log('✅ 文件格式验证通过');

      // 检查文件大小（10MB限制）
      const maxSize = 10 * 1024 * 1024 // 10MB
      console.log('文件大小:', file.raw ? file.raw.size : 'file.raw为空', 'bytes');
      console.log('最大允许大小:', maxSize, 'bytes');
      
      if (file.raw && file.raw.size > maxSize) {
        console.log('❌ 文件大小验证失败');
        this.$message.error('文件大小不能超过10MB')
        this.excelFileList = [] // 清空文件列表
        console.log('selectedFile 清空为:', this.selectedFile);
        return
      }
      console.log('✅ 文件大小验证通过');

      console.log('selectedFile 赋值前:', this.selectedFile);
      if (file.raw) {
        this.selectedFile = file.raw // 保存选中的文件
        console.log('✅ selectedFile 赋值成功:', this.selectedFile);
      } else {
        console.log('❌ file.raw 为空，无法赋值给 selectedFile');
      }
      
      this.excelFileList = fileList // 更新文件列表
      console.log('excelFileList 更新为:', this.excelFileList);
      
      // 检查按钮状态
      console.log('按钮是否禁用:', !this.selectedFile);
      console.log('=== handleFileChange 结束 ===');
    },
    // 当用户移除文件时触发
    handleRemove (file, fileList) {
      console.log('=== handleRemove 开始 ===');
      console.log('移除的file:', file);
      console.log('移除后的fileList:', fileList);
      console.log('selectedFile 清空前:', this.selectedFile);
      
      this.selectedFile = null
      this.excelFileList = fileList
      
      console.log('selectedFile 清空后:', this.selectedFile);
      console.log('按钮是否禁用:', !this.selectedFile);
      console.log('=== handleRemove 结束 ===');
    },
    
    // 关闭对话框时的回调
    addQuestionFileDialogClosed () {
      this.addQuestionFileDialogVisible = false
      this.selectedFile = null
      this.excelFileList = []
    },
    
    // 提交题库
    submitaddQuestionFileForm () {
      console.log('=== submitaddQuestionFileForm 开始 ===');
      console.log('当前selectedFile:', this.selectedFile);
      console.log('按钮是否应该禁用:', !this.selectedFile);
      
      // 检查文件是否选择
      if (!this.selectedFile) {
        console.log('❌ selectedFile为空，无法提交');
        this.$message.error('请上传文件')
        return
      }
      console.log('✅ selectedFile验证通过，开始上传');
      
      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '正在导入题库，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 获取当前教师ID
      const teacherId = SessionManager.getUserId()
      
      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('file', this.selectedFile)
      formData.append('teacherId', teacherId) // 添加教师ID
      
      this.$http.post('/questionFile/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data' // 必须使用 multipart/form-data
        }
      }).then(({ data: res }) => {
        loading.close(); // 关闭加载
        if (res.code === 200) {
          this.$message.success('添加题库成功')
          this.addQuestionFileDialogVisible = false
          this.selectedFile = null
          this.excelFileList = []
          // 刷新题目列表
          this.getQuestionList()
        } else {
          this.$message.error(res.message || '导入失败，请重试')
        }
      }).catch(error => {
        loading.close(); // 关闭加载
        console.error('上传失败:', error)
        this.$message.error('网络错误，请检查网络连接后重试')
      })
    },
    addHandler (file) {
      console.log('选择的文件:', file)
      // 验证文件格式和大小
      if (!this.beforeImageUpload(file)) {
        return
      }
      this.selectedFile = file
      return false // 阻止自动上传
    },
    getFullImageUrl(url) {
      if (!url) return '';
      
      // 如果URL已经是完整的地址（以http开头），则直接返回
      if (url.startsWith('http')) {
        return url;
      }
      
      // 否则添加基础URL
      return 'http://localhost:4041' + (url.startsWith('/') ? url : '/' + url);
    },
    handleUploadSuccess(response, file, fileList) {
      console.log('上传响应:', response);
      
      // 如果响应不是对象，转换为对象
      if (typeof response === 'string') {
        try {
          response = JSON.parse(response);
        } catch (e) {
          console.error('解析响应失败:', e);
        }
      }
      
      // 检查响应状态码
      if (response.code === 200 && response.data) {
        // 成功处理
        this.$message.success('图片上传成功');
        this.addQuestionForm.imageUrl = response.data;
        // 输出完整的图片URL进行调试
        console.log('图片URL设置为:', this.addQuestionForm.imageUrl);
        console.log('完整图片URL:', this.getFullImageUrl(this.addQuestionForm.imageUrl));
      } else {
        // 服务器返回错误
        let errorMsg = '图片上传失败';
        if (response.msg) {
          errorMsg += ': ' + response.msg;
        }
        this.$message.error(errorMsg);
        // 清除文件列表
        this.fileList = [];
      }
    },
    handleUploadError(err, file, fileList) {
      console.log('上传失败:', err, file, fileList)
      this.$message.error('上传失败，请重试')
    },
    async downloadTemplate() {
      console.log('开始下载模板文件...');
      this.$message.info('正在下载模板文件，请稍候...');
      
      try {
        const response = await this.$http({
          method: 'get',
          url: '/questionFile/template/download',
          responseType: 'blob', // 重要：指定响应类型为blob
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('token')
          }
        });
        
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '题库模板.xlsx');
        document.body.appendChild(link);
        link.click();
        
        // 清理
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
        
        this.$message.success('模板下载成功');
        console.log('模板下载成功');
      } catch (error) {
        console.error('下载模板失败:', error);
        this.$message.error('下载模板失败: ' + (error.response?.data?.message || error.message));
      }
      console.log('模板下载请求已发送');
    },
    handleFilePreview(file) {
      console.log('预览文件:', file);
    }
  }
}
</script>

<style scoped lang="less">
/* 高亮关键词样式 */
.highlight {
  background-color: #ffeb3b;
  color: #f56c6c;
  font-weight: bold;
  padding: 0 2px;
  border-radius: 2px;
}

/* 确保题目文本和答案中的HTML标签被正确渲染 */
.question-text-cell,
.answer-text-cell {
  /deep/ .highlight {
    background-color: #ffeb3b;
    color: #f56c6c;
    font-weight: bold;
    padding: 0 2px;
    border-radius: 2px;
  }
}

/* 分类选择框样式 */
:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-select-dropdown__item.hover) {
  background-color: #f5f7fa;
}

:deep(.add-category-option) {
  color: #409EFF;
  cursor: pointer;
  display: flex !important;
  justify-content: space-between;
  align-items: center;
}

:deep(.add-category-option:hover) {
  background-color: #f5f7fa !important;
  color: #409EFF !important;
}

:deep(.add-category-option .el-icon-plus) {
  margin-left: 10px;
  font-weight: bold;
}

:deep(.el-select-dropdown) {
  .el-select-dropdown__item {
    &.selected {
      color: #606266;
      font-weight: normal;
    }
  }
}
.question-manage-container {
  padding: 0 15px;
  
  .breadcrumb {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
  
  .box-card {
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .action-bar {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-start;
      gap: 15px;
    }
    
    .question-table {
      margin-bottom: 20px;
      
      .question-text-cell, .answer-text-cell {
        max-height: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
      }
      
      .image-preview {
        width: 80px;
        height: 80px;
        margin: 0 auto;
        
        .el-image {
          width: 100%;
          height: 100%;
          border-radius: 4px;
          border: 1px solid #ebeef5;
        }
      }
      
      .operation-buttons {
        display: flex;
        justify-content: center;
        gap: 10px;
      }
    }
    
    .pagination-container {
      text-align: center;
      margin: 20px 0;
    }
  }
  
  .question-form {
    padding: 0 20px;
    
    .form-row {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;
      
      .form-item-subject {
        flex: 2;
      }
      
      .form-item-type {
        flex: 1;
      }
    }
    
    .form-item-question,
    .form-item-answer,
    .form-item-analysis {
      margin-bottom: 25px;
    }
    
    .question-editor,
    .answer-editor,
    .analysis-editor {
      width: 100%;
      margin-bottom: 10px;
    }
    
    .option-item {
      display: flex;
      margin-bottom: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      overflow: hidden;
      
      .option-label {
        width: 120px;
        padding: 10px;
        background-color: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;
        border-right: 1px solid #dcdfe6;
      }
      
      .option-content {
        flex: 1;
        padding: 10px;
      }
    }
    
    .option-actions {
      margin-bottom: 20px;
      text-align: center;
    }
    
    .analysis-header {
      margin-bottom: 10px;
    }
    
    .form-item-difficulty {
      margin-top: 20px;
      
      .difficulty-tip {
        color: #909399;
        font-size: 12px;
        margin-top: 5px;
      }
    }
    
    .form-tip {
      margin-left: 10px;
      color: #909399;
      font-size: 13px;
    }
    
    .custom-textarea {
      width: 90%;
    }
    
    .image-uploader {
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s;
        
        &:hover {
          border-color: #409EFF;
        }
      }
      
      .el-upload-dragger {
        width: 90%;
        height: 200px;
      }
    }
    
    .image-preview-container {
      margin-top: 15px;
      display: flex;
      align-items: center;
      
      .preview-image {
        width: 200px;
        height: 200px;
        border-radius: 4px;
        border: 1px solid #ebeef5;
        object-fit: contain;
      }
      
      .image-actions {
        margin-left: 15px;
      }
    }
  }
  
  .file-upload-container {
    .excel-uploader {
      .el-upload {
        width: 100%;
      }
      
      .el-upload-dragger {
        width: 100%;
        height: 200px;
      }
    }
    
    .upload-hint {
      margin-top: 20px;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;
      
      h4 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #303133;
      }
      
      p {
        margin: 5px 0;
        color: #606266;
      }
    }
  }
  
  .custom-dialog {
    .el-dialog__header {
      padding: 20px;
      border-bottom: 1px solid #ebeef5;
      text-align: center;
    }
    
    .el-dialog__body {
      padding: 30px 20px;
    }
    
    .el-dialog__footer {
      padding: 15px 20px;
      border-top: 1px solid #ebeef5;
      text-align: center;
    }
  }
}

// 富文本编辑器样式覆盖
:deep(.w-e-toolbar) {
  border: 1px solid #dcdfe6 !important;
  border-bottom: none !important;
  border-radius: 4px 4px 0 0;
}

:deep(.w-e-text-container) {
  border: 1px solid #dcdfe6 !important;
  border-top: none !important;
  border-radius: 0 0 4px 4px;
}

:deep(.w-e-menu) {
  z-index: 2 !important;
}

// 全文对话框样式
:deep(.full-text-dialog) {
  max-width: 800px;
  
  .el-message-box__content {
    max-height: 500px;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-all;
  }
}
</style>
